package com.easyweb.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.easyweb.cache.StartUpListener;
import com.easyweb.common.Constants;
import com.easyweb.common.FileUtils;
import com.easyweb.common.PrimaryKeyGenerator;
import com.easyweb.common.PrintUtils;
import com.easyweb.model.Article;
import com.easyweb.model.ResultMsg;
import com.easyweb.model.Users;
import com.easyweb.service.ArticleService;

@Controller
@RequestMapping("/article")
public class ArticleController {
	
	private static Logger logger = LoggerFactory.getLogger(ArticleController.class);
	
	@Autowired
	private ArticleService articleService;

	@RequestMapping(value="merge",method=RequestMethod.POST)
	public String addArticle(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE)));
			return "back/frame";
		}
		String id = request.getParameter("id");
		String draft = request.getParameter("draft");
		if(StringUtils.isEmpty(draft)){
			draft = "1";
		}
		if(!"2".equals(draft)){
			draft = "1";
		}
		String title = request.getParameter("title");
		if(StringUtils.isEmpty(title)){
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("title.notnull"))));
			return "back/frame";
		}
		String description = request.getParameter("description");
		if(StringUtils.isEmpty(description)){
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("description.notnull"))));
			return "back/frame";
		}
		String content = request.getParameter("content");
		if(StringUtils.isEmpty(content)){
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("content.notnull"))));
			return "back/frame";
		}
		String navbar = request.getParameter("navbar");
		if(StringUtils.isEmpty(navbar)){
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("navbar.notnull"))));
			return "back/frame";
		}
		String tag = request.getParameter("tag");
		String path = this.getClass().getClassLoader().getResource("/").getPath();
		path = path.replace("/WEB-INF/classes", "");
		//上传图片
		List<String> uploadFile = null;
		try {
			uploadFile = FileUtils.uploadFile(request, path+Constants.COVERPATH+"/");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("image.upload.fail"))));
			return "back/frame";
		}
		if(StringUtils.isEmpty(id)){
			if(uploadFile == null || uploadFile.size() == 0){
				request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("image.upload.fail"))));
				return "back/frame";
			}
		}
		Article article = new Article();
		
		if(!StringUtils.isEmpty(id)){
			article.setId(id);
		}else{
			article.setId(PrimaryKeyGenerator.generatePrimaryKey());
			article.setCreateTime(new Date());
			article.setReadCount(0);
			article.setRecommend(2);
			article.setShowOnIndex(2);
		}
		if(uploadFile!=null&&uploadFile.size()>0){
			article.setThumbnail(Constants.COVERPATH+"/"+uploadFile.get(0));
		}
		article.setTitle(title);
		article.setDescription(description);
		article.setContent(content);
		article.setDraft(Integer.parseInt(draft));
		article.setNavbar(navbar);
		article.setTag(tag);
		article.setUpdateTime(new Date());
		int num = 0;
		if(StringUtils.isEmpty(id)){
			num = articleService.insertArticle(article);
			logger.info("新增artice成功:"+article.getId());
		}else{
			num = articleService.updateArticle(article);
			logger.info("修改artice成功:"+article.getId());
		}
		if(num > 0){
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg()));
		}else{
			request.setAttribute("result", JSONObject.toJSONString(new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("error.unkonw"))));
		}
		return "back/frame";
	}
	@RequestMapping(value="/publish",method=RequestMethod.POST)
	public void publishArticle(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String id = request.getParameter("id");
		if(StringUtils.isEmpty(id)){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		String draft = request.getParameter("draft");
		if(StringUtils.isEmpty(draft)||(!"1".equals(draft)&&!"2".equals(draft))){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		Article article = new Article();
		article.setId(id);
		article.setDraft(Integer.parseInt(draft));
		int num = articleService.updateArticle(article);
		if(num>0){
			PrintUtils.printMsg(response, new ResultMsg());
		}else{
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("error.unkonw")));
		}
	}
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public void getArticles(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String navBar = request.getParameter("navbar");
		String tag = request.getParameter("tag");
		String recommend = request.getParameter("recommend");
		String showOnIndex = request.getParameter("showOnIndex");
		String pageSize = request.getParameter("pageSize");
		String pageStart = request.getParameter("pageStart");
		Map<String, Object> map = new HashMap<String, Object>();
		if(!StringUtils.isEmpty(navBar)){
			map.put("navbar", navBar);
		}
		if(!StringUtils.isEmpty(tag)){
			map.put("tag", tag);
		}
		if(!StringUtils.isEmpty(recommend)){
			map.put("recommend", recommend);
		}
		if(!StringUtils.isEmpty(showOnIndex)){
			map.put("showOnIndex", showOnIndex);
		}
		if(!StringUtils.isEmpty(pageSize)){
			map.put("pageSize", Integer.parseInt(pageSize));
		}
		if(!StringUtils.isEmpty(pageStart)){
			map.put("start",  Integer.parseInt(pageSize)*(Integer.parseInt(pageStart)-1));
		}
		List<Article> list = articleService.getArticles(map);
		int count = articleService.getArticlesCount(map);
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("pageCount", count%Integer.parseInt(pageSize)==0?count/Integer.parseInt(pageSize):(count/Integer.parseInt(pageSize)+1));
		retMap.put("page", pageStart);
		retMap.put("article", list);
		retMap.put("navbar", StartUpListener.NAVBARMAP);
		retMap.put("tag", StartUpListener.TAGMAP);
		PrintUtils.printMsg(response, retMap);
	}
	
	@RequestMapping(value="/get",method=RequestMethod.GET)
	public void getArticleById(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String id = request.getParameter("id");
		Map<String, Object> map = new HashMap<String, Object>();
		if(StringUtils.isEmpty(id)){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		map.put("id", id);
		Article article = articleService.getArticleById(map);
		Map<String, Object> retMap = new HashMap<String, Object>();
		retMap.put("article", article);
		Map<String, Object> navMap = new HashMap<String, Object>();
		for(String key : StartUpListener.NAVBARMAP.keySet()){
			if(StartUpListener.NAVBARMAP.get(key).getShowOnIndex()==1){
				navMap.put(key, StartUpListener.NAVBARMAP.get(key));
			}
		}
		retMap.put("nav", navMap);
		retMap.put("tag", StartUpListener.TAGMAP);
		PrintUtils.printMsg(response, retMap);
	}
	@RequestMapping(value="/del",method=RequestMethod.GET)
	public void delArticle(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String id = request.getParameter("id");
		Map<String, Object> map = new HashMap<String, Object>();
		if(StringUtils.isEmpty(id)){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		map.put("id", id);
		Article article = articleService.getArticleById(map);
		int num = articleService.deleteArticleById(map);
		if(num > 0){
			//删除关联的图片
			String path = this.getClass().getClassLoader().getResource("/").getPath();
			path = path.replace("/WEB-INF/classes", "");
			FileUtils.deleteFile(path+"/"+article.getThumbnail());
			PrintUtils.printMsg(response, new ResultMsg());
		}else{
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR,null));
		}
	}
	@RequestMapping(value="/recommend",method=RequestMethod.POST)
	public void recommend(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String id = request.getParameter("id");
		if(StringUtils.isEmpty(id)){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		String recommend = request.getParameter("recommend");
		if(StringUtils.isEmpty(recommend)||(!"1".equals(recommend)&&!"2".equals(recommend))){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		Article article = new Article();
		article.setId(id);
		article.setRecommend(Integer.parseInt(recommend));
		int num = articleService.updateArticle(article);
		if(num > 0){
			PrintUtils.printMsg(response, new ResultMsg());
		}else{
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR,null));
		}
	}
	
	@RequestMapping(value="/showOnIndex",method=RequestMethod.POST)
	public void showOnIndex(HttpServletRequest request,HttpServletResponse response){
		Users user = (Users) request.getSession().getAttribute("user");
		if(user == null){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, Constants.EXPIRE));
			return;
		}
		String id = request.getParameter("id");
		if(StringUtils.isEmpty(id)){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		String showOnIndex = request.getParameter("showOnIndex");
		if(StringUtils.isEmpty(showOnIndex)||(!"1".equals(showOnIndex)&&!"2".equals(showOnIndex))){
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR, StartUpListener.LANGUAGE.getProperty("id.notnull")));
			return;
		}
		Article article = new Article();
		article.setId(id);
		article.setShowOnIndex(Integer.parseInt(showOnIndex));
		int num = articleService.updateArticle(article);
		if(num > 0){
			PrintUtils.printMsg(response, new ResultMsg());
		}else{
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR,null));
		}
	}
}
